package controllers

import java.io.File

import akka.http.scaladsl.model.Uri.Path
import javax.inject.Inject
import play.api.libs.json.Json
import play.api.mvc.{AbstractController, ControllerComponents}
import utils.{TableUtils, Utils}
import org.apache.commons.io.FileUtils
import utils.TableUtils.pageForm

import scala.collection.mutable
import scala.jdk.CollectionConverters._

class BrowseController @Inject()(cc: ControllerComponents) extends AbstractController(cc) {

  def browsePage(name: String) = Action { implicit request =>
    Ok(views.html.browse.browsePage(name))
  }

  def detailPage(name: String, field: String, key: String) = Action { implicit request =>
    val map = TableUtils.data(name).find(x => x(field) == key).get
    val row = TableUtils.header(name).map { x =>
      (x, map(x))
    }
    Ok(views.html.browse.detailPage(row,name,key))
  }

  def getTableHeader(name: String) = Action { implicit request =>
    Ok(Json.toJson(TableUtils.header(name)))
  }

  def getTableData(name: String) = Action { implicit request =>
    val page = pageForm.bindFromRequest.get
    val orderX = TableUtils.dealMapDataByPage(TableUtils.data(name), page)
    val total = orderX.size
    val tmpX = orderX.slice(page.offset, page.offset + page.limit)
    val json = tmpX
    Ok(Json.obj("rows" -> json, "total" -> total))
  }


}
